package com.moleq.mgnetwork;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Vector;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class MultiCommunication {

	protected static final int IP_UNREGISTER = 0;

	protected static final int IP_REGISTER = 1;

	protected static final int IP_CONNECTED = 2;

	private static final int SHOW_COMMUNICATION_MSG = 3;

//	private ArrayList<Terminal> mTerminalList = new ArrayList<Terminal>();

//	private Handler mhandler;

	private FileHandler fileHandler;
	private ConnectHandler connectHandler;

//	private Vector mlst = new Vector();

	public String localIP;

//	private IMessage logMessage;
	
	private CommunicationCallback mCommunicationCallback = null;
/*
	public MultiCommunication() {

		Terminal user = new Terminal("192.168.1.105");
		mlst.addElement(user);

		user = new Terminal("192.168.1.116");
		user.ipAddress = "";

		mlst.addElement(user);

		user = new Terminal("192.168.1.107");
		user.ipAddress = "";

		mlst.addElement(user);

		InitFolder();

		fileHandler = new FileHandler();
		fileHandler.start();

		// folderMonitor = new FolderMonitor();

		connectHandler = new ConnectHandler();
		connectHandler.start();

	}
	*/
	
	public MultiCommunication(CommunicationCallback communicationCallback){
		this.mCommunicationCallback = communicationCallback;
		
		InitFolder();

		fileHandler = new FileHandler();
		fileHandler.start();

		connectHandler = new ConnectHandler();
		connectHandler.start();
	}

	private void InitFolder() {
		String inbox = Constant.SDCARD_IN_BOX;
		String outbox = Constant.SDCARD_OUT_BOX;

		File folder = new File(inbox);
		if (!folder.exists()) {
			folder.mkdirs();
			Log.i("LogDemo", "mkdir");
		}

		folder = new File(outbox);
		if (!folder.exists()) {
			folder.mkdirs();
			Log.i("LogDemo", "mkdir");
		}

	}
	
	private final Handler communicationHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			
			switch (msg.what) {
			case IP_CONNECTED:
				if (mCommunicationCallback != null) 
				mCommunicationCallback.ipAddressConnected(msg.obj.toString(),(Boolean) msg.obj);
				break;
			case IP_REGISTER:
				if (mCommunicationCallback != null) 
				mCommunicationCallback.register(msg.obj.toString());
				break;
			case IP_UNREGISTER:
				if (mCommunicationCallback != null) 
				mCommunicationCallback.unRegister(msg.obj.toString());
				break;
			case SHOW_COMMUNICATION_MSG:
				//
				if (mCommunicationCallback != null) 
				mCommunicationCallback.showLogMessage(msg.obj.toString());
				break;

			default:
				break;
			}
			
		}
	};

//	public void setMessageListener(IMessage listener) {
//		this.logMessage = listener;
//	}
	
	public void pingIp(String ipAddress){
		connectHandler.pingIp(ipAddress);
	}

	public void sendFile(String ipAddress, String fileName) {
		fileHandler.sendFile(ipAddress, fileName);
	}

	public void sendFiles(final String idAddress, final Vector<String> fileLst) {

		new Thread() {
			@Override
			public void run() {
				for (int i = 0; i < fileLst.size(); i++) {
					showMsg("sending file ->" + fileLst.get(i));
					sendFile(idAddress, fileLst.get(i));
				}
			}
		}.start();

	}

	public void sendFileByPath(final String ipAddress, final String filePath) {
		// String outFile = Constants.OUT_FOLDER + "";// +"/test.txt";

		new Thread() {
			@Override
			public void run() {
				File outBoxFile = new File(filePath);

				File[] files = outBoxFile.listFiles();
				for (int i = 0; i < files.length; i++) {

					sendFile(ipAddress, files[i].getAbsolutePath());
				}
			}
		}.start();

	}

//	public void setHandler(Handler handler) {
//		this.mhandler = handler;
//	}

	public void setMyIP(String ipAddress) {
		localIP = ipAddress;
	}

	public void parsePackageMessage(String recvPkg) {

		if (recvPkg.equals(""))
			return;

		showMsg("Parse Package Message....\n");
		PackageMessage pkgMsg = new PackageMessage();
		pkgMsg.parseCommand(recvPkg);

		showMsg("Parsed Package Message Action -> " + pkgMsg.action + "\n");

		if (pkgMsg.action.equals(Constant.CMD_PING_IP)) {
			
			Message msg = new Message();
			msg.what = MultiCommunication.IP_REGISTER;
			msg.obj = pkgMsg.fromIp;
			communicationHandler.sendMessage(msg );
			
			System.out.println("receive pkg ->" + pkgMsg.toCommand());
			showMsg("To do command ping ip...\n");

			PackageMessage newpkgMsg = new PackageMessage();
			newpkgMsg.action = Constant.CMD_UPDATE_ME;
			newpkgMsg.fromIp = localIP;
			newpkgMsg.toIp = pkgMsg.fromIp;
			newpkgMsg.dataContent = "update me ->";
			// sendMsg( newpkgMsg.toIp,newpkgMsg.toCommand());
			sendPackageMessage(newpkgMsg);


		} else if (pkgMsg.action.equals("SendFile")) {
			showMsg("received content->[" + pkgMsg.toCommand() + "]");

		} else if (pkgMsg.action.equals(Constant.CMD_UPDATE_ME)) {
			showMsg("To do command update me...\n");

			Message msg = new Message();
			msg.what = MultiCommunication.IP_REGISTER;
			msg.obj = pkgMsg.fromIp;
			communicationHandler.sendMessage(msg );
			
		}
	}
/*
	public void Register(String ipAddress) {

		for (int i = 0; i < mTerminalList.size(); i++) {
			if (mTerminalList.get(i).ipAddress.equals(ipAddress)) {
				mTerminalList.get(i).online = true;
				break;
			}
		}
	}

	public void unRegister(String ipAddress) {
		for (int i = 0; i < mTerminalList.size(); i++) {
			if (mTerminalList.get(i).ipAddress.equals(ipAddress)) {
				mTerminalList.get(i).online = false;
				break;
			}
		}
	}

*/
	
	/*
	public void setConnectTerminal(ArrayList<Terminal> terminals) {
		this.mTerminalList = terminals;
	}

	public boolean isOnline(Terminal terminal) {
		boolean result = false;
		if (mTerminalList != null) {
			for (int i = 0; i < mTerminalList.size(); i++) {
				if (mTerminalList.get(i).ipAddress.equals(terminal.ipAddress)) {
					result = true;
					break;
				}
			}
		}
		return result;
	}

	public void sendFiles(String ipAddress, String files) {

	}
	*/

	public void showMsg(String strMsg) {
		Message msg = new Message();
		msg.what = SHOW_COMMUNICATION_MSG;
		msg.obj = strMsg;
communicationHandler.sendMessage(msg);
	}

	/*
	 * 
	 * mutil conncet model
	 */
	private class ConnectHandler extends Thread {

		private ServerSocket sSocket = null;
		private Socket clientSocket = null;
		private InetSocketAddress isa;

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();

			try {
				sSocket = new ServerSocket(Constant.CMM_PORT);
				System.out.println("connect handler socket started...");
				while (!sSocket.isClosed() && null != sSocket) {
					Socket socket = sSocket.accept();
					socket.setSoTimeout(5000);
					new ProcessReceivePackage(socket).start();
				}

			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				showMsg(e.getMessage());
			}

		}

		private class ProcessReceivePackage extends Thread {

			private Socket socket = null;

			public ProcessReceivePackage(Socket socket) {
				this.socket = socket;
			}

			@Override
			public void run() {
				// TODO Auto-generated method stub
//				super.run();

				showMsg("start receive package......"+socket.getInetAddress().toString());
				
				OutputStream output = null;
				InputStream input = null;
				String recvPkg = "";

				try {

					byte[] recvCmd = new byte[Constant.bufferSize];
					input = socket.getInputStream();
					while ((input.read(recvCmd)) != -1) {
						recvPkg += new String(recvCmd);
					}

					showMsg(" receive content ->[" + recvPkg + "]");

				} catch (Exception e) {
					e.printStackTrace();
					showMsg(e.getMessage());
				} finally {
					try {
						if (null != input)
							input.close();
						if (null != output)
							output.close();
						if (!socket.isClosed())
							socket.close();
					} catch (Exception e1) {
						e1.printStackTrace();
						showMsg(e1.getMessage());
					}
				}

				parsePackageMessage(recvPkg);

			}

		}

		public void sendPackageMessage(final PackageMessage pkgMsg) {
			new Thread() {
				@Override
				public void run() {
					try {
						showMsg("Connecthandler.sendMsg ->" + pkgMsg.toIp);
						clientSocket = new Socket();
						isa = new InetSocketAddress(pkgMsg.toIp, Constant.CMM_PORT);
						clientSocket.connect(isa, 5000);

						OutputStream output = null;
						InputStream input = null;
						if (clientSocket.isConnected()) {

							final byte[] sendCmd = pkgMsg.toCommand().getBytes();

							output = clientSocket.getOutputStream();// 构造一个输出流
							output.write(sendCmd);// 把头数据包发给对方
							output.flush();
							sleep(1000);// sleep 1秒钟，等待对方处理完

							System.out.println("send pkg ->" + pkgMsg.toCommand());
							showMsg("send pkg ->" + pkgMsg.toCommand());

						}

					} catch (Exception e) {
						e.printStackTrace();
						showMsg("error ->" + e.getMessage());
					} finally {
						try {
							// if (clientIn != null) {
							// clientIn.close();
							// }
							// if (clientOut != null) {
							// clientOut.close();
							// }
							if (clientSocket != null) {
								clientSocket.close();
							}
						} catch (Exception e) {
							e.printStackTrace();
							showMsg("error ->" + e.getMessage());
						}
					}
				}

			}.start();

		}
		
		
		public void pingIp(String ipAddress){
			try {
				showMsg("Connecthandler.pingIp ->" + ipAddress);
				clientSocket = new Socket();
				isa = new InetSocketAddress(ipAddress, Constant.CMM_PORT);
				clientSocket.connect(isa, 5000);

				if (clientSocket.isConnected()) {

					Message msg = new Message();
					msg.what = MultiCommunication.IP_REGISTER;
					msg.obj = ipAddress;
					communicationHandler.sendMessage(msg );
				
					showMsg("connect succeed ->" + ipAddress);
					sleep(1000);// sleep 1秒钟，等待对方处理完
				}

			} catch (Exception e) {
//				e.printStackTrace();
//				showMsg("Connecthandler.pingIp  error ->" + e.getMessage());
				Message msg = new Message();
				msg.what = MultiCommunication.IP_UNREGISTER;
				msg.obj = ipAddress;
				communicationHandler.sendMessage(msg );
			} finally {
				try {
					if (clientSocket != null) {
						clientSocket.close();
					}
				} catch (Exception e) {
//					e.printStackTrace();
//					showMsg("Connecthandler.pingIp  error ->" + e.getMessage());
					Message msg = new Message();
					msg.what = MultiCommunication.IP_UNREGISTER;
					msg.obj = ipAddress;
					communicationHandler.sendMessage(msg );
				}
			}
		}

		public void sendMsg(String ipAddress, String msg) {
			try {
				showMsg("Connecthandler.sendMsg ->" + ipAddress);
				clientSocket = new Socket();
				isa = new InetSocketAddress(ipAddress, Constant.CMM_PORT);
				clientSocket.connect(isa, 5000);

				OutputStream output = null;
				InputStream input = null;
				if (clientSocket.isConnected()) {

					PackageMessage pkgMsg = new PackageMessage();
					pkgMsg.action = Constant.CMD_PING_IP;
					pkgMsg.fromIp = localIP;
					pkgMsg.toIp = ipAddress;
					pkgMsg.dataContent = msg;

					final byte[] sendCmd = pkgMsg.toCommand().getBytes();

					output = clientSocket.getOutputStream();// 构造一个输出流
					output.write(sendCmd);// 把头数据包发给对方
					output.flush();
					sleep(1000);// sleep 1秒钟，等待对方处理完

					System.out.println("send pkg ->" + pkgMsg.toCommand());
					showMsg("send pkg ->" + pkgMsg.toCommand());

				}

			} catch (Exception e) {
				e.printStackTrace();
				showMsg("error ->" + e.getMessage());
			} finally {
				try {
					// if (clientIn != null) {
					// clientIn.close();
					// }
					// if (clientOut != null) {
					// clientOut.close();
					// }
					if (clientSocket != null) {
						clientSocket.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
					showMsg("error ->" + e.getMessage());
				}
			}

		}

		public void release() {
			try {
				System.out.println("File handler socket closed ...");
				if (null != sSocket)
					sSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
				showMsg(e.getMessage());
			}
		}
	}

	/*
	 * send and receive file module
	 */
	private class FileHandler extends Thread {

		private InetSocketAddress isa;
		private Socket clientSocket;
		public final static int PER_SEND_SIZE = 1024 * 100;
		private int blockNum = 1;
		private DataInputStream clientIn = null;
		private DataOutputStream clientOut = null;
		private ServerSocket sSocket = null;

		public FileHandler() {

		}

		@Override
		public void run() {
			super.run();

			try {
				sSocket = new ServerSocket(Constant.FILE_HANDLER_PORT);
				System.out.println("File handler socket started ...");
				while (sSocket != null && !sSocket.isClosed()) {
					Socket socket = sSocket.accept();
					socket.setSoTimeout(5000);
					new SaveFileToDisk(socket).start();

				}

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		// save file to disk
		private class SaveFileToDisk extends Thread {
			public final static int PER_RECEIVE_SIZE = 1024 * 100;
			private Socket socket = null;
			private DataInputStream dis = null;
			private DataOutputStream dos = null;

			public SaveFileToDisk(Socket socket) {
				this.socket = socket;

				try {
					dis = new DataInputStream(socket.getInputStream());
					dos = new DataOutputStream(socket.getOutputStream());
				} catch (IOException e) {
					e.printStackTrace();
				}

			}

			public boolean initFile(File tempFile, File parentFile, long fileSize) {
				if (tempFile.exists()) {
					return true;
				}
				if (parentFile.isDirectory()) {
					creat(tempFile, fileSize);
					return true;
				} else {
					boolean isCreate = parentFile.mkdirs();
					if (isCreate) {
						creat(tempFile, fileSize);
						return true;
					} else {
						return false;
					}
				}
			}

			public void creat(File targetFile, long fileLength) {
				long length = fileLength;// 指定写入文件文件大小
				byte[] buffer = new byte[PER_RECEIVE_SIZE];// 缓冲区 1024 bytes
				FileOutputStream fos;
				try {
					fos = new FileOutputStream(targetFile);
					while (true) { // 建立缓冲区
						if (length > PER_RECEIVE_SIZE) { // 将缓冲区字节写入文件
							try {
								fos.write(buffer);// 写入缓冲
								length = length - PER_RECEIVE_SIZE;
							} catch (IOException e) {
								e.printStackTrace();
							}
						} else {
							byte[] buf = new byte[(int) length];
							System.arraycopy(buffer, 0, buf, 0, (int) length);
							try {
								fos.write(buf);
								fos.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
							break;
						}
					}
				} catch (FileNotFoundException e1) {
					e1.printStackTrace();
				}
			}

			public boolean isContinue(DataInputStream dis) {
				boolean flag = false;
				String command;
				try {
					command = dis.readUTF();
					System.out.println(command);
					if ("Continue".equals(command)) {
						flag = true;
					}
				} catch (IOException e) {
					e.printStackTrace();
					flag = false;
				}
				return flag;
			}

			public void closeSocket(DataInputStream serverIn, DataOutputStream serverOut, Socket socket) throws IOException {
				if (serverIn != null) {
					serverIn.close();
				}
				if (serverOut != null) {
					serverOut.close();
				}
				if (socket != null) {
					socket.close();
				}
			}

			@Override
			public void run() {
				super.run();

				try {
					String command = dis.readUTF();
					DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

					if (command == null || !command.contains("MoleQInfo")) {
						return;
					}

					showMsg(" start receive file ->");

					String fileName = new String(command.replaceAll("(.+<FileName>|<\\/FileName>\\S+)", "").toString().getBytes("UTF-8"), "UTF-8");
					String fileSize = new String(command.replaceAll("(.+<FileLength>|<\\/FileLength>\\S+)", "").toString().getBytes("UTF-8"), "UTF-8");
					String offset = new String(command.replaceAll("(.+<FilePointerStart>|<\\/FilePointerStart>\\S+)", "").toString().getBytes("UTF-8"), "UTF-8");
					String endset = new String(command.replaceAll("(.+<FilePointerEnd>|<\\/FilePointerEnd>\\S+)", "").toString().getBytes("UTF-8"), "UTF-8");

					File tempFile = new File(Constant.SDCARD_IN_BOX, fileName + ".temp");
					File parentFile = tempFile.getParentFile();
					boolean isCreate = initFile(tempFile, parentFile, Long.valueOf(fileSize));
					if (!isCreate) {
						closeSocket(dis, dos, socket);
					}
					String readyCommand = "ready=1";
					writeUTF(dos, readyCommand);

					String startCommand = readUTF(dis);
					if ("sendStart".contains(startCommand)) {
						RandomAccessFile randomAccessFile = new RandomAccessFile(tempFile, "rw");

						long curPoint = Long.valueOf(offset);
						long endPoint = Long.valueOf(endset);
						byte[] buffer = null;
						while (curPoint < endPoint && isContinue(dis)) {
							if ((endPoint - curPoint + 1 < PER_RECEIVE_SIZE)) {
								buffer = new byte[(int) (endPoint - curPoint + 1)];
							} else {
								buffer = new byte[(int) (PER_RECEIVE_SIZE)];
							}
							int amount;
							long perLength = 0;
							while ((amount = dis.read(buffer)) != -1) {
								randomAccessFile.seek(curPoint);
								randomAccessFile.write(buffer, 0, amount);
								curPoint += amount;
								perLength += amount;
								if (perLength == buffer.length) {
									break;
								} else if (perLength > buffer.length) {
									System.out.println("perLength" + perLength + "\tbuffer" + buffer.length);
									System.out.println("传输出错");
								}
							}
							System.out.println(" 指针位置 " + curPoint + " , 大小" + fileSize + "\t" + (curPoint == endPoint) + "\tendPoint:" + endPoint);
							writeUTF(dos, "SerGotIt");
							if (curPoint == endPoint + 1) {
								writeUTF(dos, "receiveEnd");

								showMsg(" file receive End!->");

								// closeRandomAccessFile(randomAccessFile);
								randomAccessFile.close();

								// ******* Ming *****
								if (tempFile.exists()) {
									File newFile = new File(Constant.SDCARD_IN_BOX, fileName);
									tempFile.renameTo(newFile);
								}

								// ******************
								break;
							} else if (curPoint > endPoint) {
								System.out.println("curPoint" + curPoint + "\tendPoint" + endPoint);
								System.out.println("文件传输出错");
								showMsg(" send file error ->");
								break;
							}
						}
					}

				} catch (SocketException e) {
					System.out.println("client is closed!");
					showMsg(" client is closed!->" + e.getMessage());
					// clients.remove(this);
				} catch (EOFException e) {
					System.out.println("client is closed!");
					showMsg(" client is closed!->" + e.getMessage());
					// clients.remove(this);
				} catch (IOException e) {
					e.printStackTrace();
					showMsg(" client is closed!->" + e.getMessage());
				} finally {
					try {
						if (dis != null)
							dis.close();
						if (dos != null)
							dos.close();
						if (socket != null)
							socket.close();
					} catch (IOException e) {
						e.printStackTrace();
						showMsg(" client is closed!->" + e.getMessage());
					}
				}
			}

		}

		public void writeUTF(DataOutputStream dos, String command) throws IOException {
			dos.writeUTF(command);
			dos.flush();
		}

		public void writeBuffer(DataOutputStream dos, byte[] buffer) throws IOException {
			dos.write(buffer);
			dos.flush();
		}

		public String readUTF(DataInputStream dis) throws IOException {
			return dis.readUTF();
		}

		public String[] getFileInfos(String fileName, long offset, long endset, long fileSize, long lastModifyTime) {
			String[] fileInfos = new String[blockNum];
			fileInfos[0] = "MoleQInfo";
			fileInfos[0] += "<FileName>" + fileName + "</FileName>";
			fileInfos[0] += "<FilePointerStart>" + offset + "</FilePointerStart>";
			fileInfos[0] += "<FilePointerEnd>" + endset + "</FilePointerEnd>";
			fileInfos[0] += "<FileLength>" + fileSize + "</FileLength>";
			fileInfos[0] += "<LastModifyTime>" + lastModifyTime + "</LastModifyTime>";
			return fileInfos;
		}

		public void sendFile(final String terminalIp, final String filePath) {

			// OutputStream output = null;
			// InputStream input = null;

			try {

				showMsg(" connect ->" + terminalIp);
				clientSocket = new Socket();
				isa = new InetSocketAddress(terminalIp, Constant.FILE_HANDLER_PORT);
				clientSocket.connect(isa, 5000);

				if (clientSocket.isConnected()) {

					InputStream input = clientSocket.getInputStream();
					OutputStream output = clientSocket.getOutputStream(); // 发送文件
					clientIn = new DataInputStream(new BufferedInputStream(input));
					clientOut = new DataOutputStream(new BufferedOutputStream(output));
					File tempFile = new File(filePath);
					String fileName = tempFile.getName();

					showMsg(" start send file ->" + filePath);

					long fileSize = tempFile.length();
					long lastModifyTime = tempFile.lastModified();
					long offset = 0; // 区块起始位置
					long endset = fileSize - 1; // 区块结束位置
					String[] fileInfos = getFileInfos(fileName, offset, endset, fileSize, lastModifyTime);
					writeUTF(clientOut, fileInfos[0]);
					while (true) {
						String command = readUTF(clientIn);
						if (!command.contains("ready=1")) {
							continue;
						}
						writeUTF(clientOut, "sendStart");
						RandomAccessFile randomAccessFile = new RandomAccessFile(tempFile, "r");
						long curPoint = offset;
						byte[] buffer = null;
						while (curPoint < endset) {
							writeUTF(clientOut, "Continue");
							int length = 0;
							try {
								randomAccessFile.seek(curPoint);
								if (endset - curPoint + 1 < PER_SEND_SIZE) {
									buffer = new byte[(int) (endset - curPoint + 1)];
								} else {
									buffer = new byte[PER_SEND_SIZE];
								}
								length = randomAccessFile.read(buffer);
								if (length == buffer.length) {
									writeBuffer(clientOut, buffer);
									for (;;) {
										String serGotItCommand = readUTF(clientIn);
										if ("SerGotIt".equals(serGotItCommand)) {
											break;
										}
									}
									curPoint += length;
									System.out.println("curPoint:" + curPoint + "\tfileSize:" + fileSize);
									if (curPoint == fileSize) {
										System.out.println("发送完成");
										showMsg("send file complete...");
										break;
									}
								}
							} catch (Exception e) {
								e.printStackTrace();
								break;
							}
						}
						String endCommand = readUTF(clientIn);
						System.out.println(endCommand);
						if ("receiveEnd".equals(endCommand)) {
							System.out.println("发送指令完成");
							writeUTF(clientOut, "sendEnd");
							showMsg("send end....");

							showMsg("-> delete file " + tempFile.getAbsoluteFile());
							tempFile.delete();
							break;
						}
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
				showMsg("error ->" + e.getMessage());
			} finally {
				try {
					if (clientIn != null) {
						clientIn.close();
					}
					if (clientOut != null) {
						clientOut.close();
					}
					if (clientSocket != null) {
						clientSocket.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
					showMsg("error ->" + e.getMessage());
				}
			}

		}

	}

	public void sendMsg(String tmpIP, String string) {
		connectHandler.sendMsg(tmpIP, string);

	}

	public void sendPackageMessage(PackageMessage pkgMsg) {
		connectHandler.sendPackageMessage(pkgMsg);
	}
	
	public interface CommunicationCallback {
		public void ipAddressConnected( String ipAddress,boolean isOnline);
		public void register(String ipAddress);
		public void unRegister(String ipAddress);
		public void showLogMessage(String strMsg);
	}

	

}
